<template>
  <div class="data-map-container">
    <!-- 侧边栏 -->
    <div class="map-sidebar">
      <!-- 搜索 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索表名"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 数据库列表 -->
      <div class="database-tree">
        <h4>数据库</h4>
        <el-tree
          ref="databaseTreeRef"
          :data="databaseList"
          :props="treeProps"
          :default-expanded-keys="['doris']"
          node-key="id"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <el-icon>
                <component :is="getNodeIcon(data.type)" />
              </el-icon>
              <span class="node-label">{{ data.label }}</span>
              <span v-if="data.type === 'table'" class="table-count">
                ({{ data.rowCount || 0 }})
              </span>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 筛选选项 -->
      <div class="filter-section">
        <h4>筛选</h4>
        
        <div class="filter-item">
          <label>表类型</label>
          <el-checkbox-group v-model="filters.tableTypes" @change="applyFilters">
            <el-checkbox label="fact">事实表</el-checkbox>
            <el-checkbox label="dim">维度表</el-checkbox>
            <el-checkbox label="ods">贴源表</el-checkbox>
            <el-checkbox label="dws">汇总表</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="filter-item">
          <label>更新频率</label>
          <el-checkbox-group v-model="filters.updateFrequency" @change="applyFilters">
            <el-checkbox label="realtime">实时</el-checkbox>
            <el-checkbox label="daily">每日</el-checkbox>
            <el-checkbox label="weekly">每周</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 图例 -->
      <div class="legend-section">
        <h4>图例</h4>
        <div class="legend-items">
          <div class="legend-item">
            <div class="legend-color fact-table"></div>
            <span>事实表</span>
          </div>
          <div class="legend-item">
            <div class="legend-color dim-table"></div>
            <span>维度表</span>
          </div>
          <div class="legend-item">
            <div class="legend-color ods-table"></div>
            <span>贴源表</span>
          </div>
          <div class="legend-item">
            <div class="legend-color dws-table"></div>
            <span>汇总表</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="map-content">
      <!-- 工具栏 -->
      <div class="map-toolbar">
        <div class="toolbar-left">
          <el-button-group>
            <el-button :type="viewMode === 'graph' ? 'primary' : ''" @click="setViewMode('graph')">
              <el-icon><Share /></el-icon>
              关系图
            </el-button>
            <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="setViewMode('list')">
              <el-icon><List /></el-icon>
              列表视图
            </el-button>
          </el-button-group>
        </div>

        <div class="toolbar-right">
          <el-tooltip content="自动布局">
            <el-button @click="autoLayout">
              <el-icon><MagicStick /></el-icon>
            </el-button>
          </el-tooltip>
          
          <el-tooltip content="重置视图">
            <el-button @click="resetView">
              <el-icon><RefreshLeft /></el-icon>
            </el-button>
          </el-tooltip>
          
          <el-tooltip content="全屏显示">
            <el-button @click="toggleFullscreen">
              <el-icon><FullScreen /></el-icon>
            </el-button>
          </el-tooltip>

          <el-dropdown @command="handleExport">
            <el-button>
              <el-icon><Download /></el-icon>
              导出
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="png">导出为 PNG</el-dropdown-item>
                <el-dropdown-item command="svg">导出为 SVG</el-dropdown-item>
                <el-dropdown-item command="json">导出为 JSON</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 图形视图 -->
      <div v-show="viewMode === 'graph'" class="map-canvas" ref="canvasRef">
        <DataLineageGraph 
          :tables="filteredTables"
          :lineages="lineageData"
          @table-click="handleTableClick"
          @table-hover="handleTableHover"
        />
      </div>

      <!-- 列表视图 -->
      <div v-show="viewMode === 'list'" class="map-list">
        <el-table :data="filteredTables" stripe height="100%">
          <el-table-column label="表名" prop="name" min-width="200">
            <template #default="{ row }">
              <div class="table-name-cell">
                <div class="table-type-indicator" :class="row.type"></div>
                <div>
                  <div class="table-name">{{ row.name }}</div>
                  <div class="table-comment">{{ row.comment || '暂无描述' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="类型" prop="type" width="100">
            <template #default="{ row }">
              <el-tag :type="getTableTypeTagType(row.type)" size="small">
                {{ getTableTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="行数" prop="rowCount" width="120">
            <template #default="{ row }">
              {{ formatNumber(row.rowCount) }}
            </template>
          </el-table-column>

          <el-table-column label="大小" prop="dataSize" width="100" />

          <el-table-column label="更新时间" prop="lastUpdated" width="180">
            <template #default="{ row }">
              {{ formatTime(row.lastUpdated) }}
            </template>
          </el-table-column>

          <el-table-column label="依赖" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getDependencyCount(row.id) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewLineage(row)">
                查看血缘
              </el-button>
              <el-button size="small" @click="viewTableDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 表详情对话框 -->
    <TableDetailDialog 
      v-model="tableDetailVisible"
      :table-id="currentTableId"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import DataLineageGraph from './components/DataLineageGraph.vue'
import TableDetailDialog from './components/TableDetailDialog.vue'
import { formatTime } from '@/utils/date'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const viewMode = ref('graph')
const canvasRef = ref(null)
const databaseTreeRef = ref(null)
const tableDetailVisible = ref(false)
const currentTableId = ref(null)

// 筛选条件
const filters = reactive({
  tableTypes: ['fact', 'dim', 'ods', 'dws'],
  updateFrequency: ['realtime', 'daily', 'weekly']
})

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 数据库树结构
const databaseList = ref([
  {
    id: 'doris',
    label: 'Doris 数据仓库',
    type: 'database',
    children: [
      {
        id: 'fact_orders',
        label: 'fact_orders',
        type: 'table',
        tableType: 'fact',
        rowCount: 1540000,
        parent: 'doris'
      },
      {
        id: 'fact_sales',
        label: 'fact_sales',
        type: 'table',
        tableType: 'fact',
        rowCount: 890000,
        parent: 'doris'
      },
      {
        id: 'dim_customer',
        label: 'dim_customer',
        type: 'table',
        tableType: 'dim',
        rowCount: 25000,
        parent: 'doris'
      },
      {
        id: 'dim_product',
        label: 'dim_product',
        type: 'table',
        tableType: 'dim',
        rowCount: 12000,
        parent: 'doris'
      },
      {
        id: 'ods_user_behavior',
        label: 'ods_user_behavior',
        type: 'table',
        tableType: 'ods',
        rowCount: 5600000,
        parent: 'doris'
      },
      {
        id: 'dws_daily_summary',
        label: 'dws_daily_summary',
        type: 'table',
        tableType: 'dws',
        rowCount: 365,
        parent: 'doris'
      }
    ]
  }
])

// 表数据
const tableData = ref([
  {
    id: 'fact_orders',
    name: 'fact_orders',
    comment: '订单事实表',
    type: 'fact',
    rowCount: 1540000,
    dataSize: '2.3GB',
    lastUpdated: new Date(Date.now() - 3600000),
    x: 100,
    y: 100
  },
  {
    id: 'fact_sales',
    name: 'fact_sales',
    comment: '销售事实表',
    type: 'fact',
    rowCount: 890000,
    dataSize: '1.8GB',
    lastUpdated: new Date(Date.now() - 7200000),
    x: 300,
    y: 100
  },
  {
    id: 'dim_customer',
    name: 'dim_customer',
    comment: '客户维度表',
    type: 'dim',
    rowCount: 25000,
    dataSize: '45MB',
    lastUpdated: new Date(Date.now() - 86400000),
    x: 100,
    y: 300
  },
  {
    id: 'dim_product',
    name: 'dim_product',
    comment: '产品维度表',
    type: 'dim',
    rowCount: 12000,
    dataSize: '28MB',
    lastUpdated: new Date(Date.now() - 86400000),
    x: 300,
    y: 300
  },
  {
    id: 'ods_user_behavior',
    name: 'ods_user_behavior',
    comment: '用户行为贴源表',
    type: 'ods',
    rowCount: 5600000,
    dataSize: '8.2GB',
    lastUpdated: new Date(Date.now() - 1800000),
    x: 500,
    y: 100
  },
  {
    id: 'dws_daily_summary',
    name: 'dws_daily_summary',
    comment: '日汇总表',
    type: 'dws',
    rowCount: 365,
    dataSize: '2MB',
    lastUpdated: new Date(Date.now() - 3600000),
    x: 200,
    y: 500
  }
])

// 血缘关系数据
const lineageData = ref([
  {
    source: 'ods_user_behavior',
    target: 'fact_orders',
    type: 'etl'
  },
  {
    source: 'dim_customer',
    target: 'fact_orders',
    type: 'join'
  },
  {
    source: 'dim_product',
    target: 'fact_sales',
    type: 'join'
  },
  {
    source: 'fact_orders',
    target: 'dws_daily_summary',
    type: 'aggregate'
  },
  {
    source: 'fact_sales',
    target: 'dws_daily_summary',
    type: 'aggregate'
  }
])

// 计算属性
const filteredTables = computed(() => {
  let result = tableData.value

  // 搜索筛选
  if (searchKeyword.value) {
    result = result.filter(table => 
      table.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (table.comment && table.comment.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    )
  }

  // 类型筛选
  result = result.filter(table => 
    filters.tableTypes.includes(table.type)
  )

  return result
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const applyFilters = () => {
  // 筛选逻辑已在计算属性中处理
}

const setViewMode = (mode) => {
  viewMode.value = mode
}

const handleNodeClick = (data) => {
  if (data.type === 'table') {
    currentTableId.value = data.id
    tableDetailVisible.value = true
  }
}

const handleTableClick = (table) => {
  viewLineage(table)
}

const handleTableHover = (table) => {
  console.log('Hover table:', table)
}

const viewLineage = (table) => {
  router.push(`/data-map/lineage/${table.id}`)
}

const viewTableDetail = (table) => {
  currentTableId.value = table.id
  tableDetailVisible.value = true
}

const autoLayout = () => {
  console.log('自动布局')
}

const resetView = () => {
  console.log('重置视图')
}

const toggleFullscreen = () => {
  console.log('切换全屏')
}

const handleExport = (command) => {
  console.log('导出:', command)
}

const getDependencyCount = (tableId) => {
  return lineageData.value.filter(line => 
    line.source === tableId || line.target === tableId
  ).length
}

// 工具方法
const getNodeIcon = (type) => {
  const icons = {
    'database': 'Database',
    'table': 'Grid'
  }
  return icons[type] || 'Document'
}

const getTableTypeLabel = (type) => {
  const labels = {
    'fact': '事实表',
    'dim': '维度表',
    'ods': '贴源表',
    'dws': '汇总表'
  }
  return labels[type] || type
}

const getTableTypeTagType = (type) => {
  const types = {
    'fact': 'primary',
    'dim': 'success',
    'ods': 'warning',
    'dws': 'info'
  }
  return types[type] || 'info'
}

const formatNumber = (num) => {
  if (!num) return '0'
  return num.toLocaleString()
}

// 生命周期
onMounted(() => {
  // 初始化
})
</script>

<style scoped>
.data-map-container {
  height: 100%;
  display: flex;
}

.map-sidebar {
  width: 300px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  padding: 16px;
  overflow-y: auto;
}

.search-section {
  margin-bottom: 20px;
}

.database-tree h4,
.filter-section h4,
.legend-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
}

.node-label {
  flex: 1;
}

.table-count {
  font-size: 12px;
  color: #909399;
}

.filter-section {
  margin: 20px 0;
}

.filter-item {
  margin-bottom: 16px;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 13px;
  color: #606266;
}

.legend-section {
  margin-top: 20px;
}

.legend-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
}

.legend-color.fact-table { background: #409eff; }
.legend-color.dim-table { background: #67c23a; }
.legend-color.ods-table { background: #e6a23c; }
.legend-color.dws-table { background: #909399; }

.map-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.map-toolbar {
  height: 48px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.map-canvas,
.map-list {
  flex: 1;
  position: relative;
  background: #f8f9fa;
}

.table-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-type-indicator {
  width: 8px;
  height: 40px;
  border-radius: 4px;
}

.table-type-indicator.fact { background: #409eff; }
.table-type-indicator.dim { background: #67c23a; }
.table-type-indicator.ods { background: #e6a23c; }
.table-type-indicator.dws { background: #909399; }

.table-name {
  font-weight: 600;
  color: #303133;
}

.table-comment {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
</style> 